﻿using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace Jinndev {

    /// <summary>
    /// 按原图尺寸适配组件大小
    /// </summary>
    [ExecuteInEditMode]
    public class ImageFitter : MonoBehaviour {

        [Serializable]
        public class FitEvent : UnityEvent<Vector2> { }

        [Tooltip("更改图片时是否自动适配")]
        public bool autoFit = true;
        [Tooltip("适配编剧")]
        public RectOffset fitPadding;
        [Tooltip("适配事件")]
        public FitEvent onFit = new FitEvent();

        private bool needFit = false;
        private Texture _texture;
        private RawImage rawImage;

        private void Awake() {
            rawImage = GetComponent<RawImage>();
            if (rawImage != null) {
                _texture = rawImage.texture;
            }
        }

        private void OnDestroy() {
            _texture = null;
            rawImage = null;
        }

        private void Update() {
            if (autoFit && rawImage != null) {
                if (_texture != rawImage.texture) {
                    _texture = rawImage.texture;
                    needFit = true;
                }
            }

            if (needFit) {
                FitParent();
                needFit = false;
            }
        }

        private void OnEnable() {
            if (autoFit) {
                needFit = true;
            }
        }

        public void FitParent() {
            if (rawImage != null) {
                if (UIUtil.RawImageFitParent(rawImage, fitPadding)) {
                    onFit?.Invoke(GetComponent<RectTransform>().sizeDelta);
                }
            }
        }

    }

}